package com.tenqian.crm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tenqian.CONSTANT;
import com.tenqian.Result;
import com.tenqian.crm.domain.TqUser;
import com.tenqian.crm.repository.TqUserRepository;
import com.tenqian.crm.service.TqUserService;
import com.tenqian.enums.ResultEnum;
import com.tenqian.exception.UserException;
import com.tenqian.utils.HttpClientUtils;
import com.tenqian.utils.ResultUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
@SuppressWarnings("unchecked")
public class TqUserServiceImpl implements TqUserService {
    Logger logger = LoggerFactory.getLogger(TqUserServiceImpl.class);
    @Autowired
    TqUserRepository tqUserRepository;
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public List<TqUser> findAll() {
        return null;
    }

    @Override
    public Page pageData(Specification<TqUser> specification, Pageable pageable) {
        return null;
    }

    @Override
    public void save(Iterable<TqUser> iterable) {

    }

    @Override
    public Result save(TqUser tqUser) {
        //参数不全
        if (tqUser == null || StringUtils.isBlank(tqUser.getPassword())
                || StringUtils.isBlank(tqUser.getNickName())
                || StringUtils.isBlank(tqUser.getTelephone())) {
            return ResultUtil.error(ResultEnum.REGIST_ERROR);
        }
        //手机号被占用
        if (findByTelephone(tqUser) != null) {
            return ResultUtil.error(ResultEnum.DUPLICATE_PHONENUMBER_ERROR);
        }
        tqUserRepository.save(tqUser);
        //注册环信
        //得到token
        registIM(tqUser);
        return ResultUtil.success(tqUser);
    }

    private void registIM(TqUser tqUser) {
        //注册环信
        //得到token
        Map map = new HashMap();
        map.put("grant_type", "client_credentials");
        map.put("client_id", CONSTANT.IM_CLIENT_ID);
        map.put("client_secret", CONSTANT.IM_CLIENT_SECRET);
        JSONObject jsonObject = new JSONObject(map);
        jsonObject = HttpClientUtils.httpPost(CONSTANT.IM_TOKEN_URL, jsonObject);
        //注册用户
        Map headerMap = new HashMap();
        //设置token请求头
        headerMap.put("Bearer", jsonObject.get("access_token"));
        //用户参数
        map = new HashMap();
        map.put("username", tqUser.getId());
        map.put("password", tqUser.getPassword());
        jsonObject = new JSONObject(map);
        HttpClientUtils.httpPost(CONSTANT.IM_REGIST_URL, jsonObject, headerMap);
    }

    @Override
    public Result login(TqUser tqUser) {
        TqUser tqUser1 = tqUserRepository.findByUsernameAndPassword(tqUser.getUsername(), tqUser.getPassword());
        if (tqUser1 == null) {
            return ResultUtil.error(ResultEnum.LOGIN_ERROR);
        }
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set("token:" + token, tqUser1.getId());
        Map resultMap = new HashMap();
        resultMap.put("user", tqUser1);
        resultMap.put("token", token);
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result delToken(String token) {
        redisTemplate.delete("token:" + token);
        return ResultUtil.success();
    }

    @Override
    public TqUser findByTelephone(TqUser tqUser) {
        return tqUserRepository.findByTelephone(tqUser.getTelephone());
    }

    @Override
    public TqUser findUserByToken(String token) {
        String id = redisTemplate.opsForValue().get("token:" + token);
        if (StringUtils.isBlank(id)) {
            throw new UserException("登录已过期");
        }
        return tqUserRepository.findOne(id);

    }

    @Override
    public Result updateHeadImg(String token, String headImg) {
        TqUser user = findUserByToken(token);
        //删除原来的老头像
        if (StringUtils.isNotBlank(user.getHeadImg())) {
            HttpClientUtils.httpGet(CONSTANT.MEDIA_URL + "/upload/delFile?path=" + user.getHeadImg());
        }
        user.setHeadImg(headImg);
        user = tqUserRepository.save(user);
        return ResultUtil.success(user.getHeadImg());
    }

    @Override
    public Result addFriend(String id, String friendId) {
        TqUser host = tqUserRepository.findOne(id);
        TqUser friend = tqUserRepository.findOne(friendId);
        host.getFriends().add(friend);
        friend.getFriends().add(host);
        tqUserRepository.save(host);
        tqUserRepository.save(friend);
        return ResultUtil.success();
    }

    @Override
    public Result findByNickNameOrTelephone(String q) {
        //昵称模糊,手机号精确
        return ResultUtil.success(tqUserRepository.findTop10ByNickNameLikeOrTelephone("%" + q + "%", q));
    }


    @Override
    public Result findFriendsByToken(String token) {
        TqUser user = findUserByToken(token);
        if (null == user) throw new UserException("token已过期");
        return ResultUtil.success(user.getFriends());
    }

    @Override
    public Result findUserById(String id) {
        return ResultUtil.success(tqUserRepository.findOne(id));
    }

    @Override
    public Result delFriend(String id, String friendId) {
        TqUser owner = tqUserRepository.findOne(id);
        TqUser friend = tqUserRepository.findOne(friendId);
        owner.getFriends().remove(friend);
        friend.getFriends().remove(owner);
        return ResultUtil.success();
    }

    @Override
    public Result sendCode(String telephone) {
        String code = RandomStringUtils.randomNumeric(4);
        TqUser user = tqUserRepository.findByTelephone(telephone);
        if (user != null) {//用户已被注册
            ResultUtil.error(ResultEnum.DUPLICATE_PHONENUMBER_ERROR);
        }
//        int i = SendMessageUtil.sendCode(telephone, code);
//        if (i != 0) throw new RuntimeException("验证码发送失败");
        logger.info("发送验证码" + telephone + "→" + code);
        return ResultUtil.success(code);
    }

    @Override
    public void update(TqUser tqUser) {
        tqUserRepository.save(tqUser);
    }

}
